package com.renwei.yunlong.fragment;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseRefreshFragment;
import com.renwei.yunlong.bean.WorkSLABean;
import com.renwei.yunlong.event.ChartPasgeRefreseEvent;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by wangqi on 2017/9/29.
 */

public class WorkSLAFragment extends BaseRefreshFragment implements HttpTaskListener, RadioGroup.OnCheckedChangeListener {
    @Bind(R.id.rb_all)
    RadioButton rbAll;
    @Bind(R.id.rb_mouth)
    RadioButton rbMouth;
    @Bind(R.id.rb_week)
    RadioButton rbWeek;
    @Bind(R.id.rb_day)
    RadioButton rbDay;
    @Bind(R.id.rg)
    RadioGroup rg;
    @Bind(R.id.chart1)
    BarChart mChart;
    @Bind(R.id.tv_max)
    TextView tvMax;
    @Bind(R.id.tv_time)
    TextView tvTime;
    private PopupWindow popupWindow;
    private String companyCode; // 筛选公司code
    private String contractId; // 项目id
    private String detailId;
    private String endDates;
    private String startDates;
    private int type;

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.fragment_work_sla;
    }

    @Override
    protected void initView() {
        initColumnView();
        initPop();

        rg.setOnCheckedChangeListener(this);

    }

    @Override
    public void onPageCheck() {
        if (type==0){
            rbAll.toggle();
        }else{
            initData();
        }
    }

    /**
     * 筛选
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onScreen(ChartPasgeRefreseEvent event) {
        companyCode = event.getTargetCompanyCode();
        contractId = event.getTargetProjecyCode();
        detailId = event.getTargetServiceCode();

        initData();
    }

    private void initPop() {
        if (popupWindow == null) {
            View view = getActivity().getLayoutInflater().inflate(R.layout.pop_work_sla, null);
            popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);
            popupWindow.setBackgroundDrawable(new ColorDrawable(0000000000));
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mChart.highlightValue(null,true);
                }
            });
        }
    }

    private void initColumnView() {
        mChart.getDescription().setEnabled(false);

        // if more_black than 60 entries are displayed in the chart, no values will be
        // drawn
        mChart.setMaxVisibleValueCount(1);
        mChart.setDoubleTapToZoomEnabled(false);

        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);

        mChart.setDrawBarShadow(false);
        mChart.setDrawGridBackground(false);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setEnabled(false);
        xAxis.setDrawGridLines(false);

        YAxis yAxis = mChart.getAxisRight();
        yAxis.setDrawGridLines(false);
        yAxis.setEnabled(false);

        YAxis yAxisleft = mChart.getAxisLeft();
        yAxisleft.setStartAtZero(true);
        yAxisleft.setAxisLineColor(Color.parseColor("#00000000"));
        yAxisleft.setLabelCount(7, false);
        yAxisleft.setTextColor(Color.parseColor("#828A99"));
        // add a nice and smooth animation
        mChart.animateY(1500);

        mChart.getLegend().setEnabled(false);
        mChart.setFitBars(true);
    }

    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            map.put("serviceProviderCode", companyCode);
        } else if ("2".equals(companyType)) {
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            map.put("ownerCode", companyCode);
            map.put("contractId", contractId);
        }
        map.put("dateFlag",type+"");
        map.put("startDates", startDates);
        map.put("endDates", endDates);
        map.put("detailId", detailId);
        ServiceRequestManager.getManager().getWorkSLA(getContext(), JsonMapUtil.mapToJson(map), this);

    }

    private void setData(final WorkSLABean bean) {
        tvMax.setText("已解决工单：" + bean.getRows().getTotalNum());
        tvTime.setText(bean.getRows().getTimeSlot());
        mChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                float y = e.getY();
                if (y == 0) {
                    return;
                }
                // 展示 pop
                showPopup(e.getX(), bean);
            }

            @Override
            public void onNothingSelected() {
            }
        });
        setChartData(bean.getRows().getSlaResponseRate(), bean.getRows().getSlaArriveRate(), bean.getRows().getSlaDealtRate());
    }

    private void setChartData(String slaResponseRate, String slaArriveRate, String slaDealtRate) {
        ArrayList<BarEntry> yVals1 = new ArrayList<>();
        yVals1.add(new BarEntry(2, Float.parseFloat(TextUtils.isEmpty(slaResponseRate) ? "0" : slaResponseRate)));
        yVals1.add(new BarEntry(4, Float.parseFloat(TextUtils.isEmpty(slaArriveRate) ? "0" : slaArriveRate)));
        yVals1.add(new BarEntry(6, Float.parseFloat(TextUtils.isEmpty(slaDealtRate) ? "0" : slaDealtRate)));

        BarDataSet set1 = new BarDataSet(yVals1, "Data Set");
        set1.setColors(Color.parseColor("#689DF8"));
        set1.setDrawValues(false);

        ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
        dataSets.add(set1);
        BarData data = new BarData(dataSets);

        mChart.setData(data);

        mChart.invalidate();
    }

    private String formatTime(String time) {
        if ("0".equals(time)) {
            return "0";
        }
        float v = 0;
        if (time.endsWith("min")) {
            time = time.substring(0, time.length() - 3);
            String[] hs = time.split("h");
            if (hs.length == 2) {
                v = Float.parseFloat(hs[1]) / 60;
                v = Float.parseFloat(hs[0]) + v;
            } else {
                v = Float.parseFloat(hs[0]) / 60;
            }
        } else if (time.endsWith("h")) {
            String[] hs = time.split("h");
            v = Float.parseFloat(hs[0]) / 60;
        }
        return v + "";
    }

    private void showPopup(float x, WorkSLABean bean) {
        View view = popupWindow.getContentView();
        TextView tv1 = view.findViewById(R.id.tv_1);
        TextView tv2 = view.findViewById(R.id.tv_2);
        TextView tv3 = view.findViewById(R.id.tv_3);
        if (x == 2f) { //响应
            tv1.setText("响应达标数量：" + bean.getRows().getIsSlaResponse());
            tv2.setText("响应达标率：" + bean.getRows().getSlaResponseRate()+"%");
            tv3.setText("平均响应时长：" + bean.getRows().getSlaResponseTime());
        } else if (x == 4f) { // 到场
            tv1.setText("到场达标数量：" + bean.getRows().getIsSlaArrive());
            tv2.setText("到场达标率：" + bean.getRows().getSlaArriveRate()+"%");
            tv3.setText("平均到场时长：" + bean.getRows().getSlaArriveTime());
        } else if (x == 6f) { //处理
            tv1.setText("处理达标数量：" + bean.getRows().getIsSlaDealt());
            tv2.setText("处理达标率：" + bean.getRows().getSlaDealtRate()+"%");
            tv3.setText("平均处理时长：" + bean.getRows().getSlaDealtTime());
        }
        popupWindow.showAsDropDown(tvMax, 0, 60, Gravity.RIGHT);

    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        switch (checkedId) {
            case R.id.rb_all:
                type= 1;
                break;
            case R.id.rb_mouth:
                type= 2;
                break;
            case R.id.rb_week:
                type= 3;
                break;
            case R.id.rb_day:
                type= 4;
                break;
        }
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                WorkSLABean value = new Gson().fromJson(result, WorkSLABean.class);
                int code = value.getMessage().getCode();
                if (code == 200) {
                    setData(value);
                } else {
                    setChartData("", "", "");
                    showCenterInfoMsg(value.getMessage().getMessage());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        setChartData("", "", "");
    }
}
